package com.wangfei.lecture.apachemina.test;

import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("127.0.0.1",8887);

            //构建IO
            InputStream is = s.getInputStream();
            OutputStream os = s.getOutputStream();

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            //向服务器端发送一条消息
            bw.write("测试客户端和服务器通信，服务器接收到消息返回到客户端\n");
            bw.flush();
            s.shutdownOutput();
            //读取服务器返回的消息
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String mess = br.readLine();

            System.out.println("服务器："+mess);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String exchange(String host, int port) throws Exception {
        //calling the constructor of the socket class
        Socket socket = new Socket();
        InetAddress inetAddress=InetAddress.getByName(host);
        //calling the constructor of the SocketAddress class
        SocketAddress socketAddress=new InetSocketAddress(inetAddress, port);
        //binding the socket with inetAddress and port
        socket.bind(socketAddress);
        //the connection will not establish without binding the socket with bind() method
        socket.connect(socketAddress);
        OutputStream os = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));

        return null;
    }
}